/**
 * FileUpld.java
 *
 * Copyright (c) 2009 viorelt All Rights Reserved.
 *
 * This source file may not be copied, modified or redistributed,
 * in whole or in part, in any form or for any reason, without the express
 * written consent of viorelt .
 **/
package ro.prjmanager.core.list;

import org.directwebremoting.WebContextFactory;
import org.directwebremoting.io.FileTransfer;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.web.context.support.WebApplicationContextUtils;
import ro.prjmanager.core.service.Service;

import java.io.InputStream;


@SuppressWarnings({"unchecked"})
public class FileUpldDown {
    public void upload(String attName, FileTransfer uploadFile) {
        try {
            InputStream is = uploadFile.getInputStream();
            WebContextFactory.get().getSession().setAttribute(attName, is);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String download(Integer id, String attFile, String serviceName) {
        StringBuilder file = new StringBuilder("");
        Service service = (Service) WebApplicationContextUtils.getRequiredWebApplicationContext(WebContextFactory.get().getServletContext()).getBean(serviceName);

        byte[] b = (byte[]) new BeanWrapperImpl(service.load(id)).getPropertyValue(attFile);
        for (byte b_ : b) {
            file = file.append((char) b_);
        }


        return file.toString().replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\n", "<br>");
    }


}
